package org.je.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.je.log.JLog;

/**
 * 以GZip方式进行压缩和解压
 * 
 * @author fanyifeng 2012-11-13
 */
public class GZipUtil
{
	/**
	 * @param src
	 * @param dest
	 */
	public static void compress(InputStream src, OutputStream dest) {
		GZIPOutputStream out = null;
		try {
			out = new GZIPOutputStream(dest);
			byte[] tem = new byte[2048];
			int len = 0;
			while ((len = src.read(tem)) > -1) {
				out.write(tem, 0, len);
			}
			out.finish();
		} catch (IOException ex) {
			throw new RuntimeException("gzip-compress-error", ex);
		} finally {
			closeAll(src, out, dest);
		}
	}

	/**
	 * @param src
	 * @param dest
	 */
	public static void uncompress(InputStream src, OutputStream dest) {
		GZIPInputStream in = null;
		try {
			in = new GZIPInputStream(src);
			byte[] tem = new byte[2048];
			int len = 0;
			while ((len = in.read(tem)) > -1) {
				dest.write(tem, 0, len);
			}
		} catch (IOException ex) {
			throw new RuntimeException("gzip-uncompress-error", ex);
		} finally {
			closeAll(in, src, dest);
		}
	}

	/**
	 * @param b
	 * @return byte[]
	 */
	public static byte[] compress(byte[] b) {
		if (b == null) {
			throw new NullPointerException("b-is-null");
		}
		ByteArrayInputStream src = new ByteArrayInputStream(b);
		ByteArrayOutputStream dest = new ByteArrayOutputStream();
		compress(src, dest);
		return dest.toByteArray();
	}

	/**
	 * @param b
	 * @return byte[]
	 */
	public static byte[] uncompress(byte[] b) {
		if (b == null) {
			throw new NullPointerException("b-is-null");
		}
		ByteArrayInputStream src = new ByteArrayInputStream(b);
		ByteArrayOutputStream dest = new ByteArrayOutputStream();
		uncompress(src, dest);
		return dest.toByteArray();
	}

	private static void closeAll(Closeable... ios) {
		for (Closeable io : ios) {
			try {
				if (io != null) {
					io.close();
				}
			} catch (Exception ex) {
				JLog.error(ex);
			}
		}
	}
}
